import { useNavigate } from "react-router-dom";
import useGlobalConext from "./GlobalContext";
import useMessageBox from "./Modal/MessageBox_Context";

function textToParagraphs(text) {
    if (!text) return text;
    return text.split("\n").map((line, index) => {
        return <p key={index}>{line}</p>;
    });
}

function useRequireLogin(needAdmin = false) {
    const [context, _] = useGlobalConext();
    const navigate = useNavigate();
    const showMessageBox = useMessageBox();
    if (!context.user.id) {
        navigate('/login');
        return false;
    }
    if (needAdmin && context.user.role !== 'admin') {
        showMessageBox('权限不足', '需要管理员权限。', 'ok')
         .then(() => navigate('/'));
        return false;
    }
    return true;
}

export { textToParagraphs, useRequireLogin };